const BASE_API = 'http://localhost:8080/api/books';


const USER_INFO_KEY = 'library_user_info';


async function request(url, method = 'GET', data = null, headers = {}) {

    const requestUrl = url.startsWith('http') ? url : `${BASE_API}${url}`;

    const options = {
        method: method.toUpperCase(),
        headers: {
            'Content-Type': 'application/json',
            ...headers
        }
    };

    if (data && (method === 'POST' || method === 'PUT')) {
        options.body = JSON.stringify(data);
    }

    try {

        const response = await fetch(requestUrl, options);

        if (!response.ok) {
            throw new Error(`HTTP错误：${response.status}（${response.statusText}）`);
        }

        const result = await response.json();

        if (!result.success) {
            throw new Error(result.message || '操作失败，请重试');
        }

        return result;

    } catch (error) {

        console.error(`[${method}] ${requestUrl} 请求失败：`, error.message);

        throw error;
    }
}


async function get(url, params = {}) {

    const queryParams = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
            queryParams.append(key, value);
        }
    });
    const queryString = queryParams.toString();
    const requestUrl = queryString ? `${url}?${queryString}` : url;

    return request(requestUrl, 'GET');
}


async function post(url, data) {
    return request(url, 'POST', data);
}


async function put(url, data) {
    return request(url, 'PUT', data);
}

async function del(url) {
    return request(url, 'DELETE');
}

function setLocalStorage(key, value) {
    try {
        localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
        console.error('localStorage存储失败：', error);
    }
}

function getLocalStorage(key) {
    try {
        const value = localStorage.getItem(key);
        return value ? JSON.parse(value) : null;
    } catch (error) {
        console.error('localStorage获取失败：', error);
        return null;
    }
}

function removeLocalStorage(key) {
    localStorage.removeItem(key);
}

function saveUserInfo(userInfo) {
    setLocalStorage(USER_INFO_KEY, userInfo);
}


function getUserInfo() {
    return getLocalStorage(USER_INFO_KEY);
}


function clearUserInfo() {
    removeLocalStorage(USER_INFO_KEY);
}


function isLogin() {
    const userInfo = getUserInfo();
    return !!userInfo;
}

export default {

    BASE_API,

    request,
    get,
    post,
    put,
    del,

    setLocalStorage,
    getLocalStorage,
    removeLocalStorage,

    saveUserInfo,
    getUserInfo,
    clearUserInfo,
    isLogin
};